package com.servlet.weatherincz;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import com.weatherinczbackend.Main;
import com.weatherinczbackend.exceptions.InternalErrorException;
import java.util.Calendar;
 
/**
 * AllXmlsGeneratingServlet
 * - servlet used when all years from 61 to today need to be generated (for cache)
 * - no arguments are expected
 * 
 * @author Bc. Michal Stava 255739 <255739@mail.muni.cz>
 */
@WebServlet(urlPatterns = {"/allXmlGenerator"})
public class AllXmlsGeneratingServlet extends HttpServlet {
 
    /**
     * When called, generate all years from chmi to xmls in xmls/?.xml 
     * where ? are years (1961, 1962 etc.)
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        //For 61 - 99
        for(int i=61;i<100;i++) {
            try {
                Main.initialize(String.valueOf(i), "8859_2", "UTF-8");
            } catch (InternalErrorException ex) {
                throw new ServletException("There is problem in generating xml.", ex);
            }
            out.println("19" + i + ".xml was generated." + "</br>");
        }
        
        //For 00 - today
        Calendar now = Calendar.getInstance();
        Integer todayYear = now.get(Calendar.YEAR);
        Integer todayMonth = now.get(Calendar.MONTH);
        if(todayMonth == 0) todayYear = todayYear -1;
        todayYear = Integer.valueOf(String.valueOf(todayYear).substring(2));
        for(int i=0;i<todayYear+1;i++) {
            try {
                Main.initialize(String.valueOf(i), "8859_2", "UTF-8");
            } catch (InternalErrorException ex) {
                throw new ServletException("There is problem in generating xml.", ex);
            }
            if(i<10) out.println("200" + i + ".xml was generated" + "</br>");
            else out.println("20" + i + ".xml was generated." + "</br>");
        }
        
        out.println("AllXmls were generated without problem to directory xmls." + "</br>");
    }
}